package com.yale.springbootsecuritymd5.utils;

/**
 * @(#)MD5Utils.java
 *
 * project：taiping-common
 *
 * Copyright ©2013 - 2014 太平电子商务有限公司.  All rights reserved.
 * ADDRESS: 中国 上海 浦东新区 民生路1399号 9楼
 */

import java.security.MessageDigest;

/**
 *
 *<p>Description : MD5消息加密</p>
 *<p>Date        : May 3, 2013</p>
 *<p>Remark      : </p>
 * @version
 */
public class MD5Utils {

    private static final String hexDigit[] = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
     * MD5加密信息
     *
     * @param message
     * @return 加密信息
     * @throws Exception
     *          异常
     */
    public static String encrypt(String message) throws Exception {
        return encrypt(message, "MD5");
    }

    // algorithm: MD5 or SHA-1
    // return string length: 32 if algorithm = MD5, or 40 if algorithm = SHA-1
    public static String encrypt(String message, String algorithm)
            throws Exception {
        if (message == null) {
            throw new Exception("message is null.");
        }
        if (!"MD5".equals(algorithm) && !"SHA-1".equals(algorithm)) {
            throw new Exception("algorithm must be MD5 or SHA-1.");
        }
        byte[] buffer = message.getBytes();

        // The SHA algorithm results in a 20-byte digest, while MD5 is 16 bytes
        // long.
        MessageDigest md = MessageDigest.getInstance(algorithm);

        // Ensure the digest's buffer is empty. This isn't necessary the first
        // time used.
        // However, it is good practice to always empty the buffer out in case
        // you later reuse it.
        md.reset();

        // Fill the digest's buffer with data to compute a message digest from.
        md.update(buffer);

        // Generate the digest. This does any necessary padding required by the
        // algorithm.
        byte[] digest = md.digest();

        // Save or print digest bytes. Integer.toHexString() doesn't print
        // leading zeros.
        StringBuffer hexString = new StringBuffer();
        String sHexBit = null;
        for (int i = 0; i < digest.length; i++) {
            sHexBit = Integer.toHexString(0xFF & digest[i]);
            if (sHexBit.length() == 1) {
                sHexBit = "0" + sHexBit;
            }
            hexString.append(sHexBit);
        }
        return hexString.toString();
    }

    /**
     * MD5的算法在RFC1321 中定义 在RFC 1321中，给出了Test suite用来检验你的实现是否正确： MD5 ("") =
     * d41d8cd98f00b204e9800998ecf8427e MD5 ("a") =
     * 0cc175b9c0f1b6a831c399e269772661 MD5 ("abc") =
     * 900150983cd24fb0d6963f7d28e17f72 MD5 ("message digest") =
     * f96b697d7cb7938d525a2f31aaf161d0 MD5 ("abcdefghijklmnopqrstuvwxyz") =
     * c3fcd3d76192e4007dfb496cca67e13b 传入参数：一个字节数组 传出参数：字节数组的 MD5 结果字符串
     */
    public static String getMD5(byte[] source) {
        String s = null;
        char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
                'e', 'f' };

        try {
            MessageDigest md = MessageDigest
                    .getInstance("MD5");
            md.update(source);
            byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数，
            // 用字节表示就是 16 个字节
            char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话，使用两个字符，
            // 所以表示成 16 进制需要 32 个字符
            int k = 0; // 表示转换结果中对应的字符位置
            for (int i = 0; i < 16; i++) { // 从第一个字节开始，对 MD5 的每一个字节
                // 转换成 16 进制字符的转换
                byte byte0 = tmp[i]; // 取第 i 个字节
                str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
                // >>>
                // 为逻辑右移，将符号位一起右移
                str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
            }
            s = new String(str); // 换后的结果转换为字符串

        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }


    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigit[d1] + hexDigit[d2];
    }

}
